package co.edu.usbcali.unidades.dataaccess.dao;

import co.edu.usbcali.unidades.dataaccess.sessionFactory.HibernateSessionFactory;
import co.edu.usbcali.unidades.modelo.Correspondencia;
import co.edu.usbcali.unidades.modelo.DtoCorrespondencia;
import co.edu.usbcali.unidades.modelo.Estado;
import co.edu.usbcali.unidades.modelo.Persona;
import co.edu.usbcali.unidades.modelo.TipoCorrespondencia;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.criterion.Example;

import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * A data access object (DAO) providing persistence and search support for
 * Correspondencia entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 *
 * @author Zathura Code Generator http://code.google.com/p/zathura
 *
 */
public class CorrespondenciaDAO implements ICorrespondenciaDAO {
    private static final Log log = LogFactory.getLog(CorrespondenciaDAO.class);

    // property constants
    //public static final String  CORASUNTO = "corAsunto";
    public static final String CORASUNTO = "corAsunto";

    //public static final String  CORCODIGO = "corCodigo";
    public static final String CORCODIGO = "corCodigo";

    private Session getSession() {
        return HibernateSessionFactory.getSession();
    }

    /**
    *
    * @param Instance
    *            Correspondencia Instance to persist
    * @throws RuntimeException
    *             when the operation fails
    */
    public void save(Correspondencia instance) {
        log.debug("saving Correspondencia instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    /**
    * @param Instance
    *            Correspondencia Instance to delete
    * @throws RuntimeException
    *             when the operation fails
    */
    public void delete(Correspondencia instance) {
        log.debug("deleting Correspondencia instance");

        try {
            getSession().delete(instance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
    *
    * @param Instance
    *            Correspondencia Instance to update
    * @throws RuntimeException
    *             when the operation fails
    */
    public void update(Correspondencia instance) {
        log.debug("updating Correspondencia instance");

        try {
            getSession().update(instance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }

    public Correspondencia findById(String id) {
        log.debug("finding Correspondencia instance with id: " + id);

        try {
            Correspondencia instance = (Correspondencia) getSession()
                                                             .get(Correspondencia.class,
                    id);

            return instance;
        } catch (RuntimeException re) {
            log.error("finding Correspondencia failed", re);
            throw re;
        }
    }

    public List<Correspondencia> findByExample(Correspondencia instance) {
        log.debug("finding Correspondencia instance by example");

        try {
            List results = getSession().createCriteria("Correspondencia")
                               .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: " +
                results.size());

            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    /**
    * Find all  Correspondencia entities with a specific property value.
    *
    * @param value
    *            the property value to match
    * @param propertyName
    *            the property to search in the instance
    * @return List< Correspondencia> found by query
        */
    public List<Correspondencia> findByProperty(String propertyName,
        Object value) {
        log.debug("finding Correspondencia instance with property: " +
            propertyName + ", value: " + value);

        try {
            String queryString = "from Correspondencia as model where model." +
                propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List<Correspondencia> findByCorAsunto(Object corAsunto) {
        return findByProperty(CORASUNTO, corAsunto);
    }

    public List<Correspondencia> findByCorCodigo(Object corCodigo) {
        return findByProperty(CORCODIGO, corCodigo);
    }

    /**
    * Find all Correspondencia entities.
    *
    * @return List<Correspondencia> all Correspondencia instances
    */
    public List<Correspondencia> findAll() {
        log.debug("finding all Correspondencia instances");

        try {
            String queryString = "from Correspondencia";
            Query queryObject = getSession().createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public List<Correspondencia> findByCriteria(String whereCondition) {
        log.debug("finding Correspondencia " + whereCondition);

        try {
            String where = ((whereCondition == null) ||
                (whereCondition.length() == 0)) ? "" : ("where " +
                whereCondition);
            final String queryString = "select model from Correspondencia model " +
                where;
            Query query = getSession().createQuery(queryString);
            List<Correspondencia> entitiesList = query.list();

            return entitiesList;
        } catch (RuntimeException re) {
            log.error("find By Criteria in Correspondencia failed", re);
            throw re;
        }
    }

    public List<Correspondencia> findPageCorrespondencia(
        String sortColumnName, boolean sortAscending, int startRow,
        int maxResults) {
        log.debug("finding Correspondencia findPageCorrespondencia");

        if ((sortColumnName != null) && (sortColumnName.length() > 0)) {
            try {
                String queryString = "select model from Correspondencia model order by model." +
                    sortColumnName + " " + (sortAscending ? "asc" : "desc");

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        } else {
            try {
                String queryString = "select model from Correspondencia model";

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        }
    }

    public Long findTotalNumberCorrespondencia() {
        log.debug("finding Correspondencia count");

        try {
            String queryString = "select count(*) from Correspondencia model";
            Query queryObject = getSession().createQuery(queryString);

            return (Long) queryObject.list().get(0);
        } catch (RuntimeException re) {
            throw re;
        }
    }
    
    public List<DtoCorrespondencia> consultarDtoCorrespondencia(String cedula) {
		Query hql = HibernateSessionFactory.getSession().createQuery("select c.corCodigo, c.tipoCorrespondencia, c.corAsunto, dt.persona,  dt.estado, dt.dtcFechaEnvio from Correspondencia c, DetalleCorrespondencia dt where (dt.persona.perCedula =:p_codigo and c.corCodigo= dt.correspondencia.corCodigo)");
		hql.setParameter("p_codigo", cedula);
		List <Object []> dt = hql.list();
		
		List<DtoCorrespondencia> dtoEncontrados = new ArrayList<DtoCorrespondencia>();
		
		for(int i =0; i <dt.size();i++){			
			DtoCorrespondencia datosDt =new DtoCorrespondencia();
			
			datosDt.setCorCodigo(dt.get(i)[0].toString());
			datosDt.setTipoCorrespondencia((TipoCorrespondencia)dt.get(i)[1]);
			datosDt.setCorAsunto(dt.get(i)[2].toString());	
			datosDt.setPersona((Persona)dt.get(i)[3]);		
			datosDt.setEstado((Estado)dt.get(i)[4]);
			datosDt.setDtcFechaEnvio((Date)dt.get(i)[5]);
			
			dtoEncontrados.add(datosDt);
			
		}
		
    	return dtoEncontrados;
	}

    
}
